﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
using System.Drawing.Imaging;
using IML;
using I = IML.Shared;

namespace IML.MVC.Models
{
    public class IMLResult : ActionResult
    {
        #region Properties
        private string _sourceText { get; set; }
        private I.ImageCompilerRequest _request { get; set; }
        private Bitmap _bitmap { get; set; }
        private bool _isSource { get; set; }
        private Graphics _g { get; set; } 
        #endregion

        #region Constructors
        public IMLResult() { _request = USFlag.Request(700, 450); _isSource = false; _buildImage(); }
        public IMLResult(string sourceText)
        {
            _isSource = true;
            _sourceText = sourceText;
            _buildImage();
        } 
        #endregion

        #region Private Methods
        private void _buildImage()
        {
            try
            {
                if (_isSource) _request = new Parser(new Lexer(_sourceText)).Parse();
                _bitmap = new Bitmap(_request.CanvasWidth, _request.CanvasHeight, PixelFormat.Format32bppArgb);
                _g = Graphics.FromImage(_bitmap);
                new ImageCompiler().DrawCanvas(_request, _g);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region ActionResult Required Methods
        public override void ExecuteResult(ControllerContext context)
        {
            HttpContextBase cb = context.HttpContext;
            cb.Response.Clear();
            cb.Response.ContentType = "image/bmp";

            try
            {
                _bitmap.Save(cb.Response.OutputStream, ImageFormat.Bmp);
                _bitmap.Dispose();
                _g.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        } 
        #endregion
    }
}
